package binarytreedemo;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2024-01-22
 * Time: 23:44
 */
public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //以穷举的方式 创建一棵二叉树出来
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;//空树是不需要遍历的
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    public void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    // 后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    public static int nodeSize;
    public void size(TreeNode root) {
        if(root == null) {
            return;//空树是不需要遍历的
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    //子问题
    public int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int tmp = size2(root.left) +
                size2(root.right)+1;
        return tmp;
    }

    public int leafSize;
    public void getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left)
                + getLeafNodeCount2(root.right);
    }

    //root的第k层有多少个节点
    public int getKLevelNodeCount(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1)+
                getKLevelNodeCount(root.right,k-1);
    }

    //O(N)
    //https://leetcode.cn/problems/maximum-depth-of-binary-tree/submissions/
    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.max(leftHeight,rightHeight) + 1;
    }


    public int getHeight2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        int rightHeight = getHeight2(root.right);

        return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
    }

    public int getHeight3(TreeNode root) {
        if(root == null) {
            return 0;
        }

        return (getHeight3(root.left) >  getHeight3(root.right)
                ? getHeight3(root.left) :  getHeight3(root.right)) + 1;
    }

    public TreeNode find(TreeNode root,int val) {
        if(root == null) return null;
        if(root.val == val) return root;

        TreeNode leftVal = find(root.left,val);
        if(leftVal != null) {
            return leftVal;
        }

        TreeNode rightVal = find(root.right,val);
        if(rightVal != null) {
            return rightVal;
        }
        return null;
    }


    //O(min(M,N))
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p != null && q == null  || p == null && q != null) {
            //结构不一样
            return false;
        }
        //上述If语句没有进来 那么说明  要么两个都是空 要么两个都不是空
        if(p == null && q == null) {
            return true;
        }
        //两个都不为空
        if(p.val != q.val ) {
            return false;
        }
        //上述代码完成 走到这里 说明p != null && q != null && 根节点值一样
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //m  n  -> O(m*n) ->
    // root这棵树的每个节点 都要和subRoot判断是否相同
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) return false;
        if(isSameTree(root,subRoot)) {
            return true;
        }
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        if(root.left == null && root.right == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //时间复杂度：O(N^2)  ->
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if(Math.abs(leftH-rightH) < 2 && isBalanced(root.left)
                && isBalanced(root.right)) {
            return true;
        }
        return false;
    }

    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getHeight22(root) >= 0;
    }

    public int getHeight22(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftHeight = getHeight22(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        int rightHeight = getHeight22(root.right);
        //刚刚已经约定 不平衡会返回负数
        if(leftHeight >= 0 && rightHeight >= 0
                && Math.abs(leftHeight-rightHeight) <= 1) {
            return Math.max(leftHeight,rightHeight) + 1;
        }else {
            //不平衡
            return -1;
        }
    }

    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        //1.结构上的判断
        if(leftTree == null && rightTree != null ||
                leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null ) {
            return true;
        }
        //2. 值
        if(leftTree.val != rightTree.val) {
            return false;
        }
        //3. 都不为空 且当前节点值一样了，继续判断左和右
        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }

    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    //把每一层 放到一个List里面
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> retList = new ArrayList<>();
        if(root == null) {
            return retList;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            //拿当前队列的节点个数来看的
            int size = queue.size();//2
            List<Character> list = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                size--;//0
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            retList.add(list);
        }
        return retList;
    }

    /*
    判断一棵树是不是完全二叉树
     */
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;//结束之后  遍历队列剩下的所有元素 是不是都是null
            }
        }
        // 遍历队列剩下的所有元素 是不是都是null
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                return false;
            }
        }
        return true;
    }

    public TreeNode lowestCommonAncestor(TreeNode root,
                                         TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(left != null && right != null) {
            return root;
        }else if(left != null){
            return left;
        }else {
            return right;
        }
    }

    /**
     *
     * @param root 根节点
     * @param node 要查找指定的节点
     * @param stack 存储路径
     * @return 返回值
     */
    public boolean getPath(TreeNode root, TreeNode node,
                           Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flgLeft = getPath(root.left,node,stack);
        if(flgLeft) {
            return true;
        }
        boolean flgRight = getPath(root.right,node,stack);
        if(flgRight) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root,
                                          TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        /*ArrayDeque;
        LinkedList;*/
        getPath(root,p,stack1);
        getPath(root,q,stack2);

        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2) {
            int size = size1-size2;
            while (size != 0) {
                stack1.pop();
                size--;
            }
        }else {
            int size = size2-size1;
            while (size != 0) {
                stack2.pop();
                size--;
            }
        }

        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            if(stack1.peek().equals(stack2.peek())) {
                return stack1.pop();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;
    }

    /*
    class Solution {

    public  int preIndex ;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    private TreeNode buildTreeChild(int[] preorder, int[] inorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        //1、创建根节点
        TreeNode root =  new TreeNode(preorder[preIndex]);
        //2. 在中序遍历的字符串当中 找到当前根节点的下标
        int rootIndex = findRootIndex(inorder,inBegin,inEnd,preorder[preIndex]);
        preIndex++;//F
        //3. 分别创建左子树和右子树
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inEnd);
        return root;
    }

    private int findRootIndex(int[] inorder,int inBegin,int inEnd,int key) {
        for(int i = inBegin; i <= inEnd;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
     */

    /*
    class Solution {
    public int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;

        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }


    private TreeNode buildTreeChild(int[] postorder, int[] inorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        //1、创建根节点
        TreeNode root =  new TreeNode(postorder[postIndex]);
        //2. 在中序遍历的字符串当中 找到当前根节点的下标
        int rootIndex = findRootIndex(inorder,inBegin,inEnd,postorder[postIndex]);
        postIndex--;//F
        //3. 分别创建右子树、左子树
        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inEnd);
        root.left = buildTreeChild(postorder,inorder,inBegin,rootIndex-1);
        return root;
    }

    private int findRootIndex(int[] inorder,int inBegin,int inEnd,int key) {
        for(int i = inBegin; i <= inEnd;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
     */

    public String tree2str(TreeNode root) {
        StringBuilder sbu = new StringBuilder();
        tree2strChild(root,sbu);
        return sbu.toString();
    }

    public void tree2strChild(TreeNode root,StringBuilder sbu) {
        if(root == null) {
            return;
        }
        sbu.append(root.val);

        //1、先递归左树
        if(root.left != null) {
            sbu.append("(");
            tree2strChild(root.left,sbu);
            sbu.append(")");
        }else {
            //root == 4
            if(root.right == null) {
                return;
            }else {
                sbu.append("()");
            }
        }
        //2、递归右树
        if(root.right != null) {
            sbu.append("(");
            tree2strChild(root.right,sbu);
            sbu.append(")");
        }else {
            return;
        }
    }
    /*public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);

                cur = cur.left;
            }
            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }*/


    /*public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev ) {
                stack.pop();
                list.add(top.val);
                prev = top;
            }else {
                cur = top.right;
            }
        }
        return list;
    }*/
}
